package com.nbrc.service.impl;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.impl.bpmn.diagram.ProcessDiagramGenerator;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.TaskQuery;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.nbrc.helper.Pagenation;
import com.nbrc.jsonmodel.MyProcess;
import com.nbrc.jsonmodel.MyTask;
import com.nbrc.model.Myleave;
import com.nbrc.model.Role;
import com.nbrc.model.User;
import com.nbrc.repo.MyleaveRepository;
import com.nbrc.repo.RoleRepository;
import com.nbrc.repo.UserRepository;
import com.nbrc.service.CommonService;
import com.nbrc.uil.HistoryProcessInstanceDiagramCmd;
@Service("commonService")
public class CommonServiceImpl implements CommonService{

	@Autowired
	@Qualifier("userRepository")
	UserRepository ur;
	@Autowired
	@Qualifier("myleaveRepository")
	MyleaveRepository mlr;
	@Autowired
	@Qualifier("roleRepository")
	RoleRepository rr;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ManagementService managementService;
	@Autowired
	private ProcessEngineFactoryBean processEngine;
	@Autowired
	private RepositoryService repositoryService;
	@Override
	public User login(String username, String userpassword) {
		// TODO Auto-generated method stub
		return ur.login(username,userpassword);
	}
	@Override
	public boolean saveLeave(Myleave leave, User user, Role role){
		// TODO Auto-generated method stub
		Role r = rr.findOne(role.getId());
		if(mlr.save(leave)!=null){
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("userbz", r.getUser().getId());
			identityService.setAuthenticatedUserId(user.getId());
			runtimeService.startProcessInstanceByKey("leave",leave.getId(),variables);
			return true;
		}
		return false;
	}
	@Override
	public Pagenation<MyProcess> allFinished(User user, int page, int rows) {
		HistoricProcessInstanceQuery hpiq = historyService.createHistoricProcessInstanceQuery().startedBy(user.getId());
		List<HistoricProcessInstance> finished = hpiq.listPage((page-1)*rows, rows);
		Pagenation<MyProcess> ph = new Pagenation<>(page,rows);
		ph.setRows(MyProcess.toProcess(finished));
		
		ph.setTotal(hpiq.list().size());
		return ph;
	}
	@Override
	public Myleave getOneMyLeave(String id) {
		// TODO Auto-generated method stub
		return mlr.findOne(id);
	}
	@Override
	public Pagenation<MyTask> getAlltaskassignee(User user, String key,
			int page, int rows) {
		// TODO Auto-generated method stub
		Pagenation<MyTask> ph = new Pagenation<>(page,rows);
		TaskQuery tasks = taskService.createTaskQuery().taskAssignee(user.getId());
		ph.setRows(MyTask.toTask(historyService,tasks.listPage((page-1)*rows, rows)));
		ph.setTotal(tasks.list().size());
		return ph;
	}
	@Override
	public void complete(String id, Map<String, Object> variables) {
		// TODO Auto-generated method stub
		taskService.complete(id, variables);
	}
	@Override
	public Pagenation<MyTask> getAlltaskCandidateGroup(Role role, String key,
			int page, int rows) {
		// TODO Auto-generated method stub
		Pagenation<MyTask> ph = new Pagenation<>(page,rows);
		TaskQuery tasks = taskService.createTaskQuery().taskCandidateGroup(role.getId());
		ph.setRows(MyTask.toTask(historyService,tasks.listPage((page-1)*rows, rows)));
		ph.setTotal(tasks.list().size());
		return ph;
	}
	@Override
	public void claim(String id,User user) {
		// TODO Auto-generated method stub
		taskService.claim(id,user.getId());
		
	}
	@Override
	public boolean oneModifyMyleave(Myleave leave,String taskid) {
		Myleave l = mlr.findOne(leave.getId());
		l.setContent(leave.getContent());
		l.setTitle(leave.getTitle());
		if(mlr.save(l)!=null){
			taskService.complete(taskid);
			return true;
		}
		return false;
	}
	@Override
	public InputStream graphHistoryProcessInstance(String processInstanceId) {
		  ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
		List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
		Context.setProcessEngineConfiguration(processEngine.getProcessEngineConfiguration());//解决文字字体
		InputStream is =ProcessDiagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds);
/*		Context.setProcessEngineConfiguration(processEngine.getProcessEngineConfiguration());//解决文字字体
*/		Command<InputStream> cmd = new HistoryProcessInstanceDiagramCmd(is,processInstanceId);
        InputStream is2 = managementService.executeCommand(cmd);
        return is2;
	}
	@Override
	public InputStream systemGraphHistoryProcessInstance(
			String processInstanceId) {
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
		List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
		Context.setProcessEngineConfiguration(processEngine.getProcessEngineConfiguration());//解决文字字体
		InputStream is =ProcessDiagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds);
        return is;
	}
}
